package com.system.enterprisemanagementsystem.filter;

import com.system.enterprisemanagementsystem.utils.JwtUtils;
import com.system.enterprisemanagementsystem.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import org.springframework.util.StringUtils;
import java.io.IOException;

/**
 * 令牌校验过滤器
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String url = request.getRequestURL().toString();

        // 1. 放行登录请求
        if (url.contains("login")) {
            log.info("登录请求 , 直接放行");
            chain.doFilter(request, response);
            return;
        }

        // 2. 获取 token
        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)) {
            log.info("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        try {
            // 3. 解析 token
            Claims claims = JwtUtils.parseToken(jwt);
            Integer userId = claims.get("id", Integer.class);
            if (userId != null) {
                UserContext.setUserId(userId);
            }

            // 4. 放行请求
            chain.doFilter(request, response);

        } catch (Exception e) {
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        } finally {
            // ⚠️ 注意：必须放在请求执行完之后再清除
            UserContext.clear();
        }
    }
}
